package com.wngbms.aop.dynamicproxy;

import com.wngbms.aop.staticproxy.DefaultEchoService;
import com.wngbms.aop.staticproxy.EchoService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibDynamicProxyDemo {

    public static void main(String[] args) {

        Enhancer enhancer = new Enhancer();
        Class<DefaultEchoService> serviceClass = DefaultEchoService.class;
        enhancer.setSuperclass(serviceClass);
        enhancer.setInterfaces(new Class[] {EchoService.class});
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                Object result = methodProxy.invokeSuper(o, objects);
                System.out.println("====");
                return result;
            }
        });

        DefaultEchoService defaultEchoService = (DefaultEchoService) enhancer.create();
        System.out.println(defaultEchoService.echo("hello world"));
    }
}
